package com.security.door.comm;

import com.security.door.model.vo.treeDataVo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TreeDataBuilder {
    List<treeDataVo> nodes = new ArrayList<>();

    public TreeDataBuilder(List<treeDataVo> nodes) {
        this.nodes = nodes;
    }

    // 构建JSON树形结构
    public List<treeDataVo> buildJSONTree() {
        return buildTree();
    }

    // 构建树形结构
    public List<treeDataVo> buildTree() {
        List<treeDataVo> treeNodes = new ArrayList<>();

        List<treeDataVo> rootNodes = getRootNodes();

        for (treeDataVo rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    // 递归子节点
    public void buildChildNodes(treeDataVo node) {
        List<treeDataVo> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (treeDataVo child : children) {
                buildChildNodes(child);
            }
            node.setNodes(children);
        }
    }
    // 获取父节点下所有的子节点
    public List<treeDataVo> getChildNodes(treeDataVo pnode) {
        return nodes.stream().filter(x -> x.getPid().equals(pnode.getId())).collect(Collectors.toList());
    }
    // 获取集合中所有的根节点
    public List<treeDataVo> getRootNodes() {
        return nodes.stream().filter((x) -> {
            return nodes.stream().filter(t -> t.getPid().equals(x.getId())).count() > 0;
        }).collect(Collectors.toList());
    }
}
